/////////////////////////////////////////////////////////////////////////////
// Name:        ax_menu_modal.cpp
// Purpose:     Modal menu class
// Author:      Julian Smart
// Modified by:
// Created:     2009-03-20
// RCS-ID:
// Copyright:   (c) Julian Smart
// Licence:     New BSD License
/////////////////////////////////////////////////////////////////////////////

#include "wx/wx.h"
#include "wx/evtloop.h"

#include "ax/ax_menu_modal.h"

IMPLEMENT_CLASS( AxModalMenu, wxEvtHandler )

AxModalMenu::AxModalMenu(AxMenuController* controller, AxMenuItem* item)
{
    Init();
    m_controller = controller;
    m_menuItem = item;
}

AxModalMenu::~AxModalMenu()
{
    if (m_eventLoop->IsRunning())
        m_eventLoop->Exit(0);
    delete m_eventLoop;

    RestorePreviousMenu();
    delete m_menu;
}

void AxModalMenu::Init()
{
    m_eventLoop = new wxEventLoop;
    m_modalShowing = false;
    m_menuItem = NULL;
    m_controller = NULL;
    m_menu = NULL;
    m_previousMenu = NULL;
}

// Starts showing the menu modally
wxString AxModalMenu::ShowModal(AxMenu* childMenu)
{
    if (m_modalShowing)
        return wxEmptyString;

    if (GetMenu() && GetController())
    {
        SetPreviousMenu(GetController()->GetCurrentMenu());

        GetMenu()->SetModal(true);
        GetController()->BeginModal();

        GetController()->ShowMenu(GetMenu(), NULL, childMenu);
        
        m_modalShowing = true;
        m_eventLoop->Run();

        GetController()->EndModal();
        
        m_modalShowing = false;

        return m_returnCode;
    }
    else
        return wxEmptyString;
}

// Terminates the modal loop
bool AxModalMenu::EndModal(const wxString& returnCode)
{
    m_returnCode = returnCode;
    
    if (m_eventLoop->IsRunning())
        m_eventLoop->Exit(0);

    m_modalShowing = false;

    return true;
}

// 'Hides' the menu (restores previous)
bool AxModalMenu::Hide()
{
    return RestorePreviousMenu();
}

bool AxModalMenu::RestorePreviousMenu()
{
    if (m_previousMenu)
    {
        if (m_controller)
            m_controller->ShowMenu(m_previousMenu, m_previousMenu->GetParent(),
                                   NULL, AxNavigationHintBack);
        m_previousMenu = NULL;
        return true;
    }
    else
        return false;
}
